import axios from "axios";
import {store} from "@/redux";
import {message} from "antd";

axios.defaults.baseURL = '/api';
axios.defaults.timeout = 50000;
axios.defaults.withCredentials = false;
axios.defaults.headers.post['Content-Type'] = 'application/json';

axios.interceptors.request.use((config) => {
	console.log("interceptors.request => url :", config.url)
	if (config.url !== '/user/login') {
		config.headers["Authorization"] = store.getState().user.token;
	}
	return config;
})

axios.interceptors.response.use(
	response => {
		console.log("interceptors.response => ", response);
		const data = response.data as Result<any>;
		if (data.code === 100200) {
			return data.result;
		}
		return response;
	},
	error => {
		// 这里处理不是2xx状态码的值
		console.log("interceptors.response.error => ", error);
		if(error.message == "Network Error"){
			message.error('网络错误');
			return Promise.reject({message: error.message})
		} else {
			console.log("response | error => ", error);
			const {status, data} = error.response;
			const result = data as Result<string>;
			switch (status) {
				case 400:
					message.error(result.result);
					break;
				default:
					message.error(result.result);
					break;
			}
			return Promise.reject(error)
		}


	}
)

export interface Result<T> {
	code: number;
	message: string;
	result: T;
}

export interface PageData<T> {
	records: T[];
	page: number;
	size: number;
	total: number;
}

// 分页返回
export type PageResult<T> = Result<PageData<T>>


const httpGet = async <T, E>(url: string, param?: E): Promise<T> => {
	const {data} = await axios.get<T>(url, {params: param})
	// console.log("httpGet", data);
	return data
}

const httpPost = async <T, E>(url: string, param: E): Promise<T> => {
	const {data} = await axios.post<T>(url, param)
	// console.log("httpPost", data);
	return data
}

const httpDelete = async <T, E>(url: string, param: E): Promise<T> => {
	const {data} = await axios.delete(url, {params: param})
	return data
}

const httpFormPost = async <T, E>(url: string, params?: E): Promise<T> => {
	const {data} = await axios.post(url, params, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	return data
}



export {httpGet, httpPost, httpDelete, httpFormPost}
